// pages/mygroup_detail/mygroup_detail.js
var util = require('../../util/util.js');
var app = getApp(); //引用app.js
var commonURL = app.data.baseURL;
var commonURLWW = app.data.testURL;
var session_key = app.data.session_key;

// var openid = app.data.openid;
var appid = app.data.appid;
var indexid = "";
var tuan_id = "";
var BTN = 0; //判断是参团还是开团按钮   2开团  其他情况参团
var animation = wx.createAnimation({
  duration: 600, //动画持续时间，单位ms，默认值 400
  timingFunction: 'linear', //linear  动画一直较为均匀 
  success: function (res) {
    // console.log(res)
  }
});
Page({
  data: {
    goodsId: null,
    groupId: null,
    gStates: '',
    "loadingDisplay": "block",
    "BTN": {
      background: "#aaa"
    },
    "price": {
      dandu: "",
      tuangou: "",
      num: ""
    },
    BTNUrl: "",
    bidtapBTN: "",
    "disabledGuige": "none",
    isKaiTuan: false, //判断是立即参团，还是新开团
    "top": {
      // msg1:"您本次参团序号:",
      // msg2:"赶快召唤小伙伴加入吧!",
      // zhuangtai:"",
      // xuhao:"1",
      // color:"green"
    },
    "detail": {
      // id:"",
      // gimg:"",
      // orderNum:"333333",
      // name:"202",
      // people:"2000人",
      // price:"0.01",
      // unit:"斤",
      // num:"2",
      // selltype:"",
      //deliverytype:""
    },
    "disabled": {
      groupNum: "none"
    },
    "moreDisplay": "none", //查看更多
    "groupNums": [
      // "11111","2222","3333","4444","5555"
    ],
    "groupPeople": {
      haveNum: "",
      nullNum: "",
      allNum: "",
      people: [{
        // img:"",
        // name:"张三",
        // num:"1",
        // time1:"2017-10-10",
        // time2:"15:30:25",
        // tell:"“好货不容易，快来跟我一起抢。”"
      }],
    },
    "Time": {
      start: {

      },
      now: {
        hours: "0",
        minutes: "0",
        seconds: "0"
      }
    },
    //index_detail页的数据
    "currentNavtab": "0",
    "navTab": ["图文详情", "商品属性"],
    "likes": [{
      // img:"../../images/index/detail1.jpg",
      // title:"苹果1苹果苹果苹果苹果苹果",
      // price:"28.00"
    }],
    "close": "none", //关闭图标属性
    "xiangqing": {
      txt: [],
      img: []
    },
    "shuxing": {
      txt: [],
      img: []
    },
    "animation": "",
    show_canvas: 'none'
  },
  onLoad: function (options) {
    console.log(options)
    var pages = getCurrentPages()    //获取加载的页面

    var currentPage = pages[pages.length - 1]    //获取当前页面的对象

    var url = currentPage.route    //当前页面url

    var options = currentPage.options    //如果要获取url中所带的参数可以查看options
    console.log(url, currentPage, pages,'当前url')
    if (options.goodsid) {
      this.setData({
        goodsId: parseInt(options.goodsid)
      })
    }
    if (options.tuan_id) {
      this.setData({
        groupId: parseInt(options.tuan_id)
      })
    }
    wx.showToast({ //loading。。。
      title: '数据加载中',
      icon: 'loading',
      duration: 10000
    })
    if (app.data.openid != "") {
      app.getUserInfo(function (userInfo) { })
      wx.getUserInfo({})
    }
    // 页面初始化 options为页面跳转所带来的参数
    indexid = options.goodsid; //商品ID
    // this.getimg();

    tuan_id = options.tuan_id; //商品ID
    // console.log('shangp',indexid);
    // console.log('tuan',tuan_id);
    this.get_code(options, this); //获取小程序码

    wx.showShareMenu({
      withShareTicket: true,
      success: function (res) {
        // 分享成功
        // console.log('shareMenu share success')
        // console.log(res);
      },
      fail: function (err) {
        // 分享失败
        //console.log(err)
      }
    })
    /** 判断场景值，1044 为转发场景，包含shareTicket 参数 */
    // console.log(options);
    // console.log(options.scene);
    if (options.scene == 1044) {
      wx.getShareInfo({
        shareTicket: options.shareTicket,
        success: function (res) {
          var encryptedData = res.encryptedData;
          var iv = res.iv;
          // console.log('转发到群组后打开');
          // console.log(encryptedData);
          // console.log(iv);
        }
      })
    }
    // this.hecheng();
  },
  onReady: function () {

  },
  onShow: function () {
    // 页面显示
    var that = this;
    that.ajaxGroup(that, () => {
      this.requestGoodsDetail();
    }); //加载团数据
    this.setData({
      disabledGuige: 'none'
    })
    wx.request({ //ajax加载猜你喜欢
      url: commonURL + 'op=goods_rand',
      data: {},
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        // console.log(res.data.list)
        if (res.data.list.length < 1) { return false }
        for (var i = 0, likes = []; i < res.data.list.length; i++) {
          var obj = {};
          obj["id"] = res.data.list[i].id;
          obj["gimg"] = res.data.list[i].gimg;
          obj["title"] = res.data.list[i].gname;
          obj["price"] = res.data.list[i].gprice;
          likes.push(obj);
        }
        setTimeout(function () {
          wx.hideToast()
        }, 1000)
        that.setData({
          "likes": likes,
          "loadingDisplay": "none",
          "BTN": { //页面加载完成后，才可以点击提交订单按钮
            background: "#e4393c",
            bindtap: that.data.bidtapBTN
          }
        })
      }
    })
  },
  onHide: function () {
    // 页面隐藏
  },
  onUnload: function () {
    // 页面关闭
  },
  onPullDownRefresh: function () { //页面下拉刷新页面
    var that = this;
    that.ajaxGroup(that);
  },
  requestGoodsDetail() {
    var that = this;
    var shuxing = [];
    var xiangqing = "";
    wx.request({ //加载图文详情和商品属性
      url: commonURL + 'op=goods_detail_yh',
      data: {
        id: that.data.detail.id,
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        //console.log(res.data);
        var data = res.data;
        if (data.params.length == 0) {
          shuxing = [{ text1: "暂无属性信息" }];
        } else {
          for (var i = 0; i < data.params.length; i++) { //获取属性信息
            var obj = {};
            obj["text1"] = data.params[i].title;
            obj["text2"] = data.params[i].value;
            shuxing.push(obj);
          }
        }
        if (data.gdesc == "") {
          (xiangqing = "暂无详情信息")
        } else {
          xiangqing = data.gdesc;
          that.setData({
            xiangqing: that.escapeHtml(xiangqing)
          })
        }
        let current = 0;
        data.param_level_info = data.param_level_info.map(item => {
          if (that.data.groupPeople.haveNum < item.groupnum) {
            current++
          }
          return {
            ...item,
            current
          }
        })
        that.setData({
          "shuxing": shuxing,
          "detail.hasoption": data.hasoption,
          "detail.selltype": data.selltype,
          "detail.group_level_status": data.group_level_status,
          "detail.param_level_info": data.param_level_info,
          "price": {
            dandu: data.oprice,
            tuangou: data.gprice,
            num: data.groupnum
          },
        });
        //console.log(that.data.detail)
      }
    })
  },
  requestShereInfo(info) {
    var that = this
    wx.getShareInfo({ //转发时获取群信息
      shareTicket: info.shareTickets[0],
      success: function (res) {
        // var session_key = wx.getStorageSync('session_key');
        var openid = wx.getStorageSync('openid');
        wx.request({
          url: commonURLWW + 'op=base64_code',
          data: {
            openid: openid,
            appid: appid,
            sessionKey: app.data.session_key,
            encryptedData: res.encryptedData,
            iv: res.iv
          },
          header: {
            'content-type': 'application/json'
          },
          success: function (res) {
            //console.log('ch成功解密');
            that.setData({
              currentGid: res.data.data.openGId
            })
          },
          fail: function (err) {
            //console.log('失败');
            //console.log(err);
          }
        })
        //console.log('拿到分享群信息');
        //console.log(res);
      },
      fail: function (res) {
        //console.log('失败')
        //console.log('error'+res)
      }
    })
  },
  groupBlock: function () {
    this.setData({
      "disabled.groupNum": "block"
    })
    animation.height("800rpx").step();
    this.setData({
      animation: animation.export()
    })
  },
  groupNone: function () {
    var that = this;
    animation.height("0").step();
    that.setData({
      animation: animation.export()
    })
    setTimeout(function () {
      that.setData({ "disabled.groupNum": "none" })
    }, 600)
  },
  switchTab: function (e) {
    //商品详情和属性的切换
    this.setData({
      currentNavtab: e.currentTarget.dataset.idx
    });
  },
  moreDisplay: function () {
    if (this.data.moreDisplay == "none") {
      this.setData({
        moreDisplay: "block"
      })
    } else {
      this.setData({
        moreDisplay: "none"
      })
    }
  },
  open: function (e) {
    //查看拼团详情
    this.setData({
      close: "block"
    })
  },
  close: function (e) {
    //关闭拼团详情
    this.setData({
      close: "none"
    })
  },
  gotoDetail: function () {
    var that = this;
    BTN = 0;
    // console.log(that.data.detail.id);
    wx.redirectTo({
      url: "../index_detail/index_detail?id=" + that.data.detail.id
    })
  },
  gotoBuy: function () {
    var that = this;
    BTN = 0;
    var dataDetail = {
      id: that.data.detail.id,
      title: that.data.detail.name,
      price: that.data.detail.price,
      img: that.data.detail.gimg,
      selltype: that.data.detail.selltype,
      deliverytype: that.data.detail.deliverytype
    }
    wx.setStorage({
      key: 'indexBuyDetail',
      data: dataDetail,
      success: function (res) {
        wx.redirectTo({
          url: "../index_buy/index_buy?istuan=true&tuan_id=" + that.data.detail.orderNum,
        })
      }
    })
  },
  gotoIndexDetail: function (e) {
    wx.redirectTo({
      url: '../index_detail/index_detail?id=' + e.currentTarget.dataset.id,
    })
  },
  onShareAppMessage: function () { //分享页面
    var that = this;
    let mid = app.data.parentMid;
    let path = '/pages/mygroup_detail/mygroup_detail?tuan_id=' + that.data.groupId + '&goodsid=' + that.data.id + "&hasoption=" + that.data.detail.hasoption;
    path = mid ? path + '&mid=' + mid + '' : path;
    return {
      title: "团购详情",
      desc: that.data.top.zhuangtai,
      path: path,
      success: function (res) {
        //console.log(res);
        //console.log('分享'+res.shareTickets[0]);
        that.requestShereInfo(res);
      },
      fail: function (res) {
        //console.log('分享失败');
      }
    }
  },
  ajaxGroup: function (that, success) {
    // complete
    BTN = 0;
    var zhuangtai = "";
    var msg1 = "";
    var msg2 = "";
    var xuhao = "";
    var color = "";
    var arr = []; //组团成员列表
    wx.request({
      url: commonURL + 'op=group_detail', //ajax获取团详情信息
      data: {
        tuan_id: tuan_id
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var data = res.data;
        that.setData({
          "detail": {
            zhuangtai: data.group.groupstatus,
            id: data.group.goodsid,
            gimg: data.group.img,
            share_image: data.group.share_image,
            orderNum: data.group.groupnumber,
            name: data.group.goodsname,
            people: data.group.nownum + "人",
            price: data.group.price,
            unit: data.group.unit,
            num: data.group.neednum,
            selltype: data.group.selltype,
            deliverytype: data.group.deliverytype
          },
          gStates: data.group.groupstatus
        })
        //console.log(that.data.gStates)
        wx.downloadFile({
          url: data.group.img,
          success: function (response) {
            wx.playVoice({
              filePath: response.tempFilePath
            })
            that.setData({
              gimg: response.tempFilePath
            })
          }
        })
        if (data.group.groupstatus == "3") {
          zhuangtai = "组团进行中";
          msg1 = "您本次参团序号:";
          msg2 = "邀请好友";
          color = "green";
          //计时器--倒计时    获取服务器时间,并存入storage
          var startTime = new Date(data.group.endtime * 1000);
          var EndTime = new Date(startTime.setHours(startTime.getHours()));
          setInterval(function () {
            var NowTime = new Date();
            var t = EndTime.getTime() - NowTime.getTime();
            var d = 0;
            var h = 0;
            var m = 0;
            var s = 0;
            if (t >= 0) {
              d = Math.floor(t / 1000 / 60 / 60 / 24);
              h = Math.floor(t / 1000 / 60 / 60 % 24) + d * 24;
              m = Math.floor(t / 1000 / 60 % 60);
              s = Math.floor(t / 1000 % 60);
              that.setData({
                "Time.now": {
                  hours: h,
                  minutes: m,
                  seconds: s
                }
              })
            }
          }, 500);
        } else if (data.group.groupstatus == "2") {
          zhuangtai = "团购成功";
          msg2 = "重开一单";
          color = "green";
          xuhao = "";

        } else if (data.group.groupstatus == "1") {
          zhuangtai = "团购失败";
          msg2 = "重新再来!";
          color = "red";
          xuhao = "";
        }
        if (data.member_list.length > 0) {
          data.member_list.forEach(function (item) {
            if (item.openid == app.data.openid) {
              BTN++;
            }
          })
          if (app.data.openid === data.member_list[0].openid) {
            BTN++;
          }

          if (data.group.groupstatus != "3") {
            that.setData({ //开团
              isKaiTuan: false,
              BTNUrl: "../index_detail/index_detail?id=",
              bidtapBTN: "gotoDetail"
            })
          } else {
            if (BTN > 0) { //开团
              that.setData({
                isKaiTuan: false,
                BTNUrl: "../index_detail/index_detail?id=",
                bidtapBTN: "gotoDetail"
              })
            } else { //参团
              msg1 = "";
              that.setData({
                isKaiTuan: true,
                BTNUrl: "../index_buy/index_buy?istuan=true",
                bidtapBTN: "gotoBuy"
              })
            }
          }
          for (var key in data.member_list) { //加载参团人员列表

            var obj = {};
            var _length = data.member_list[key].avatar.length;
            var avatar = data.member_list[key].avatar;
            if (key == 0) {
              obj.img = avatar || "../../images/mygroup/nullheader.png";
              obj.name = data.member_list[key].nickname || "";
              obj.num = key - 0 + 1;
              obj.time1 = data.member_list[key].create_date;
              obj.time2 = data.member_list[key].create_time;
              obj.tell = "“好货不容易，快来跟我一起抢。”"
            } else if (key == 1) {
              obj.img = avatar || "../../images/mygroup/nullheader.png";
              obj.name = data.member_list[key].nickname || "";
              obj.num = key - 0 + 1;
              obj.time1 = data.member_list[key].create_date;
              obj.time2 = data.member_list[key].create_time;
              obj.tell = "“立马参团，有钱就是任性。”"
            } else {
              obj.img = avatar || "../../images/mygroup/nullheader.png";
              obj.name = data.member_list[key].nickname || "";
              obj.num = key - 0 + 1;
              obj.time1 = data.member_list[key].create_date;
              obj.time2 = data.member_list[key].create_time;
            }
            if (key >= 150) {
              arr[arr.length - 4].img = "../../images/mygroup/point.png";
              break;
            }
            arr.push(obj);
          }

          if (parseInt(data.group.lacknum) > 0) { //补人头
            for (var i = 0; i < parseInt(data.group.lacknum); i++) {
              var obj = {};
              arr.push(obj);
              if (arr.length >= 150) {
                arr[arr.length - 4].img = "../../images/mygroup/point.png";
                break;
              }
            }
          }
        }
        that.setData({
          "top": {
            msg1: msg1,
            msg2: msg2,
            zhuangtai: zhuangtai,
            xuhao: (data.group.groupstatus == "3") ? xuhao : "",
            color: color
          },
          "groupPeople": {
            haveNum: data.group.nownum,
            nullNum: data.group.lacknum,
            allNum: data.group.neednum,
            people: arr
          }
        }, () => {
          success && success();
        })
      }
    })
  },
  // hecheng:function () {
  //   // util.draw(this.data.images,function (img) {  
  //   //   console.log(img);
  //   // })
  //   var that = this;
  //     //画布canvas
  //     const ctx = wx.createCanvasContext('myCanvas');

  //     ctx.drawImage('https://wx.qlogo.cn/mmopen/vi_32/DYAIOgq83ep05ABFlMU5oUc1O5Km3aefZY1KblKNTibC8qdgyRyKvcUpkBmqmZD3DxDibCSyZehZ0DC2DLeZ1neg/0', 0, 0, 120, 100)
  //     ctx.draw();

  //     ctx.setFontSize(20);
  //     ctx.fillText('NaN', 120, 100);
  //     ctx.draw();
  // },
  escapeHtml: function (text) {
    var a = text.replace(/(\&lt;)/g, "<");
    var b = a.replace(/(\&gt;)/g, ">");
    var c = b.replace(/(\&amp;)/g, "\&");
    var d = c.replace(/(\&quot;)/g, "\"");
    return d;
  },
  getimg: function () {
    var that = this;
    //生成图片
    wx.canvasToTempFilePath({
      canvasId: 'myCanvas',
      success: function (res) {
        //console.log(res.tempFilePath);
        var imgsrc = res.tempFilePath;
        //存入相册
        that.setData({
          imgg: imgsrc
        })
        // wx.saveImageToPhotosAlbum({
        //   success(res) {
        //     console.log(res);
        //     console.log(2);
        //   },
        //   complete: function (res) {
        //     console.log(res);
        //   }
        // })
        wx.previewImage({
          current: that.data.imgg, // 当前显示图片的http链接
          urls: [that.data.imgg] // 需要预览的图片http链接列表
        })
      }
    })
  },
  // imga:function(e){
  //   var that=this;

  // },
  get_code: function (options, that) {
    wx.request({ //获取二维码
      url: commonURLWW + 'op=base64_decode',
      data: {
        openid: app.data.openid,
        orderno: options.orderid,
        appid: appid,
        secret: app.data.secret,
        path: "pages/mygroup_detail/mygroup_detail",
        scene: options.orderid
      },
      method: 'GET',
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        // console.log(res);
        // console.log(res.data);

        // wx.setStorage({
        //   key:"code_img",
        //   data:res.data
        // })
        // var img = new Image(); 
        // img.crossOrigin = 'Anonymous'; //解决跨域
        // img.src=that.data.detail.gimg;
        // console.log(img.width);

        // that.setData({
        //   code_img: res.data
        // })
        wx.downloadFile({
          url: res.data,
          success: function (response) {
            wx.playVoice({
              filePath: response.tempFilePath
            })
            that.setData({
              code_img: response.tempFilePath
            })
          }
        })
      }
    })
  },
  onshow_canvas: function () {
    const ctx = wx.createCanvasContext('myCanvas')

    // ctx.draw();
    ctx.drawImage(this.data.gimg, 0, 0, 300, 150);
    ctx.drawImage(this.data.code_img, 0, 0, 150, 150);
    ctx.draw();
    this.setData({
      show_canvas: 'block'
    })
  },
  close_canvas: function () {
    this.setData({
      show_canvas: 'none'
    })
  },
  gotoBuy_tuan: function (e) {
    var that = this;

    if (that.data.detail.hasoption == "1") { //有规格产品
      //弹出规格选择框
      that.ajaxGuige(that); //加载规格数据
      that.openGuige(that, true);
    } else { //无规格产品
      if (that.data.detail.kucun < 1) {
        wx.showToast({
          title: '库存不足,无法购买',
          icon: 'loading',
          duration: 2000
        })
      } else {
        that.tiaozhuanTuan(); //调用跳转函数
      }
    }
  },
  ajaxGuige: function (that) {
    var ajaxguige = wx.getStorageSync('guige');
    if (ajaxguige.id == that.data.detail.id) { //先判断该商品规格是否存在缓存中，否则ajax加载数据
      var data = ajaxguige.allspecs;
      var currentItem = [];
      for (var i = 0; i < data.length; i++) {
        currentItem.push({ title: "", item: "-1" });
      }
      if (data.length < 1) {
        return false
      }
      that.setData({
        guige: {
          img: that.data.detail.img,
          price: "0.00",
          list: data
        },
        guigeOptions: ajaxguige.options,
        currentItem: currentItem
      })
    } else {
      wx.request({
        url: commonURL + 'op=goods_guige',
        data: {
          id: that.data.detail.id
        },
        header: {
          'content-type': 'application/json'
        },
        success: function (res) {
          console.log(res.data)
          var data = res.data.allspecs;
          var currentItem = [];
          for (var i = 0; i < data.length; i++) {
            currentItem.push({ title: "", item: "-1" });
          }
          if (data.length < 1) {
            return false
          }
          that.setData({
            guige: {
              img: that.data.detail.img,
              price: "0.00",
              list: data
            },
            guigeOptions: res.data.options,
            currentItem: currentItem
          })
          var dataguige = res.data;
          dataguige.id = that.data.detail.id;
          wx.setStorage({ //把规格存储在缓存中
            key: 'guige',
            data: dataguige,
          })
        }
      })
    }
  },
  closeGuige: function () {
    var that = this;
    animation.height("0").step();
    that.setData({
      animation: animation.export() //关闭规格选择
    })
    setTimeout(function () {
      that.setData({ disabledGuige: "none" });
    }, 600)
  },
  openGuige: function (that, istuan) { //选择规格动画
    that.setData({
      disabledGuige: "block"
    });
    animation.height("540rpx").step();
    that.setData({
      animation: animation.export(), //输出动画
      istuan: istuan
    })
  },
  tiaozhuanTuan: function () { //团购跳转函数
    var that = this
    that.data.detail['img'] = that.data.detail.gimg;
    wx.removeStorage({ key: 'address' });
    wx.setStorage({
      key: "indexBuyDetail",
      data: that.data.detail
    })
    console.log("b" + that.data.gStates)
    if (that.data.gStates == 2) {
      wx.navigateTo({
        url: '../index_buy/index_buy?istuan=true',
      })
    } else {
      wx.navigateTo({
        url: '../index_buy/index_buy?istuan=true&tuan_id=' + that.data.groupId,
      })
    }
  },
  chooseGG: function (e) { //选择规格
    var that = this;
    var title = e.currentTarget.dataset.title;
    var options = that.data.guigeOptions;
    var currentItem = that.data.currentItem;
    var key = e.currentTarget.dataset.key;
    var guige = that.data.guige;
    currentItem[key].title = title;
    currentItem[key].item = e.currentTarget.dataset.index;
    if (e.currentTarget.dataset.img) {
      guige.img = e.currentTarget.dataset.img
    } //如果规格图片存在，就替换图片
    for (var i = 0; i < options.length; i++) {
      for (var j = 0, ii = 0; j < currentItem.length; j++) {
        if (currentItem[j].title == "") {
          that.setData({
            "currentItem": currentItem,
            "guige": guige
          })
          return false;
        }
        var patt1 = new RegExp(currentItem[j].title);
        var result = patt1.test(options[i].title);
        result && ii++;
      }
      if (currentItem.length == ii) {
        var price = "";
        that.data.istuan ? price = options[i].marketprice : price = options[i].productprice;
        guige.price = price;
      }
    }
    that.setData({
      "currentItem": currentItem,
      "guige": guige
    })
  },
  gotoBuyPage: function () { //规格弹窗，确定按钮
    var that = this;
    for (var i = 0; i < that.data.currentItem.length; i++) {
      if (that.data.currentItem[i].item == "-1") { //判断是否选中规格
        wx.showToast({
          title: '请选择规格',
          icon: 'loading',
          duration: 1500
        })
        return false;
      }
    }
    wx.removeStorage({ key: 'address' });
    for (var jj = 0, title = ""; jj < that.data.currentItem.length; jj++) {
      title += ("+" + that.data.currentItem[jj].title);
    }
    var dataDetail = {
      id: that.data.detail.id,
      title: that.data.detail.title,
      price: that.data.guige.price,
      img: that.data.detail.gimg,
      selltype: that.data.detail.selltype,
      deliverytype: that.data.detail.deliverytype,
      weight: that.data.detail.weight,
      optionname: title.slice(1)
    }
    wx.setStorage({
      key: "indexBuyDetail",
      data: dataDetail
    })
    //console.log(that.data.gStates)
    if (that.data.gStates == 2) {
      wx.navigateTo({
        url: (that.data.istuan) ? '../index_buy/index_buy?istuan=true' : '../index_buy/index_buy',
      })
    } else {

      wx.navigateTo({
        url: (that.data.istuan) ? '../index_buy/index_buy?istuan=true&tuan_id=' + that.data.groupId : '../index_buy/index_buy',
      })
    }

  },
})